﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using System.Reflection;
using Thaire.Investment.Repository.Mapping;
using NHibernate.Context;

namespace Thaire.Investment.Repository
{
   public class SessionManager
    {
       //static ISessionFactory session;
       //public static ISessionFactory Instance
       //{
       //    get
       //    {

       //        if (session == null)
       //        {
       //            session = Fluently.Configure().
       //                   Database(MsSqlConfiguration.MsSql2008.ConnectionString(@"Data Source=127.0.0.1\SQLEXPRESS;Initial Catalog=investment;User ID=investment;Password=1234;").ShowSql()).
       //                       Mappings(m => m.FluentMappings.AddFromAssemblyOf<FixIncomeSecuritiesHeaderMap>()).BuildSessionFactory();
       //        }


       //        return session;


       //    }
       //}


       private readonly ISessionFactory sessionFactory;
       public static ISessionFactory SessionFactory
       {
           get { return Instance.sessionFactory; }
       }

       private ISessionFactory GetSessionFactory()
       {
           return sessionFactory;
       }

       private static SessionManager Instance
       {
           get
           {
               return NestedSessionManager.sessionManager;
           }
       }

       public static ISession OpenSession()
       {
           return Instance.GetSessionFactory().OpenSession();
       }

       public static ISession CurrentSession
       {
           get
           {
               return Instance.GetSessionFactory().GetCurrentSession();
           }
       }
       public static DateTime SystemDate
       {
           get
           {
               var session = Instance.GetSessionFactory().GetCurrentSession();
               return session.CreateSQLQuery("select getdate()").UniqueResult<DateTime>();
           }
       }


       private SessionManager()
       {
          
           sessionFactory = Fluently.Configure().
                         Database(MsSqlConfiguration.MsSql2008.ConnectionString(System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection1"].ConnectionString).ShowSql())
                         .Mappings(m => m.FluentMappings.AddFromAssemblyOf<FixIncomeSecuritiesHeaderMap>())
                             .CurrentSessionContext<ManagedWebSessionContext>()
                             .BuildSessionFactory();
       }

       class NestedSessionManager
       {
           internal static readonly SessionManager sessionManager =    new SessionManager();
       }

     
    }
}
